﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySQLStudio.DataAccess;
using System.Data;

namespace MySQLStudio.BusinessLogic
{
    public class View : BaseDatabaseObject, IColumnsContainer
    {
        private DateTime m_created;
        private DateTime? m_lastAltered;
        private String m_DEFINITION;
        private ColumnCollection m_Columns;
        private String connectionString = String.Empty;
        public DateTime Created
        {
            get { return m_created; }
            set { m_created = value; }
        }

        public DateTime? LastAltered
        {
            get { return m_lastAltered; }
            set { m_lastAltered = value; }
        }

        public String Definition
        {
            get { return m_DEFINITION; }
            set { m_DEFINITION = value; }
        }

        internal View(String name, String schema, String type, DateTime created, DateTime? lastAltered, String definer,String connectionString)
        {
            this.m_name = name;
            this.m_schema = schema;
            this.m_type = type;
            this.m_created = created;
            this.m_lastAltered = lastAltered;
            this.m_DEFINITION = definer;
            this.connectionString = connectionString;
            //m_Columns = ViewController.GetColumnsStatement(connectionString, m_schema, m_name);
        }

        public string GetSelectStatement()
        {
            StringBuilder sbSelectStatement = new StringBuilder();

            ColumnCollection columns = this.Columns;

            if (columns != null)
            {
                sbSelectStatement.Append("select \n");

                for (int i = 0; i < columns.Count; i++)
                {
                    if (i == 0)
                        sbSelectStatement.AppendFormat("\t{0}\n", columns[i].Name);
                    else
                        sbSelectStatement.AppendFormat("\t,{0}\n", columns[i].Name);
                }

                sbSelectStatement.AppendFormat(" from  {0} \n", this.m_name);
            }

            return sbSelectStatement.ToString();
        }

        #region IColumns Members

        public ColumnCollection Columns
        {
            get
            {
                if (m_Columns == null)
                {
                    m_Columns = ViewController.GetColumnsStatement(connectionString, m_schema, m_name);
                }
                return m_Columns;
            }
        }

        #endregion        
    }
}
